// 企业微信环境配置
const WECHAT_CONFIG = {
  // 企业微信配置信息（需要替换为实际值）
  CORP_ID: 'your-corp-id',
  AGENT_ID: 'your-agent-id',
  
  // API配置
  API_BASE_URL: process.env.NODE_ENV === 'production' 
    ? 'https://www.lzetyy.com:6724/api' 
    : 'https://www.lzetyy.com:6724/api',
    
  // 企业微信JS-SDK配置
  JSAPI_LIST: [
    'getContext',
    'selectEnterpriseContact',
    'openEnterpriseChat',
    'shareToExternalContact'
  ]
}

// 检测是否在企业微信环境中
export const isWeChatWork = () => {
  const ua = navigator.userAgent.toLowerCase()
  return ua.includes('wxwork') || ua.includes('micromessenger')
}

// 获取企业微信用户信息
export const getWeChatUserInfo = () => {
  return new Promise((resolve, reject) => {
    if (!isWeChatWork()) {
      reject(new Error('不在企业微信环境中'))
      return
    }

    if (typeof wx === 'undefined') {
      reject(new Error('企业微信JS-SDK未加载'))
      return
    }

    wx.ready(() => {
      wx.agentConfig({
        corpid: WECHAT_CONFIG.CORP_ID,
        agentid: WECHAT_CONFIG.AGENT_ID,
        timestamp: Math.floor(Date.now() / 1000),
        nonceStr: Math.random().toString(36).substr(2, 15),
        signature: '', // 需要后端计算签名
        jsApiList: WECHAT_CONFIG.JSAPI_LIST,
        success: (res) => {
          console.log('agentConfig success:', res)
          
          // 获取用户身份
          wx.getContext({
            success: (contextRes) => {
              console.log('getContext success:', contextRes)
              resolve({
                code: contextRes.code,
                userId: contextRes.userId || '',
                corpId: WECHAT_CONFIG.CORP_ID
              })
            },
            fail: (err) => {
              console.error('getContext fail:', err)
              reject(new Error('获取用户身份失败'))
            }
          })
        },
        fail: (err) => {
          console.error('agentConfig fail:', err)
          reject(new Error('企业微信配置失败'))
        }
      })
    })

    wx.error((err) => {
      console.error('wx error:', err)
      reject(new Error('企业微信初始化失败'))
    })
  })
}

// 企业微信登录
export const wechatLogin = async () => {
  try {
    const userInfo = await getWeChatUserInfo()
    
    // 调用后端验证接口
    const response = await fetch(`${WECHAT_CONFIG.API_BASE_URL}/Auth/wechat-login`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        code: userInfo.code
      })
    })

    const result = await response.json()
    
    if (response.status === 200 && result) {
      // 保存token到localStorage
      localStorage.setItem('token', result.token)
      localStorage.setItem('user', JSON.stringify(result.user))
      return { success: true, data: result }
    } else {
      throw new Error(result.message || '登录失败')
    }
  } catch (error) {
    console.error('企业微信登录失败:', error)
    throw error
  }
}

// 获取企业微信JS-SDK配置
export const getWeChatJsApiConfig = async (url) => {
  try {
    const response = await fetch(`${WECHAT_CONFIG.API_BASE_URL}/Auth/wechat-jsapi-config`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        url: url || window.location.href
      })
    })

    const result = await response.json()
    
    if (response.status === 200 && result) {
      return result
    } else {
      throw new Error('获取JS-SDK配置失败')
    }
  } catch (error) {
    console.error('获取企业微信JS-SDK配置失败:', error)
    throw error
  }
}

// 选择企业联系人
export const selectContact = () => {
  return new Promise((resolve, reject) => {
    if (!isWeChatWork()) {
      reject(new Error('不在企业微信环境中'))
      return
    }

    wx.selectEnterpriseContact({
      fromDepartmentId: -1, // -1表示从根部门开始
      mode: 'single', // single-单选，multi-多选
      type: ['user'], // user-成员，department-部门
      success: (res) => {
        resolve(res.result)
      },
      fail: (err) => {
        reject(err)
      }
    })
  })
}

// 分享给外部联系人
export const shareToExternal = (title, desc, link) => {
  return new Promise((resolve, reject) => {
    if (!isWeChatWork()) {
      reject(new Error('不在企业微信环境中'))
      return
    }

    wx.shareToExternalContact({
      type: 'link',
      title: title,
      desc: desc,
      link: link,
      success: (res) => {
        resolve(res)
      },
      fail: (err) => {
        reject(err)
      }
    })
  })
}

// 设置导航栏
export const setNavigationBar = (title, backgroundColor = '#1890ff') => {
  if (!isWeChatWork()) return

  wx.setNavigationBarTitle({
    title: title
  })

  wx.setNavigationBarColor({
    frontColor: '#ffffff',
    backgroundColor: backgroundColor
  })
}

// 显示加载提示
export const showLoading = (title = '加载中...') => {
  if (!isWeChatWork()) return

  wx.showLoading({
    title: title,
    mask: true
  })
}

// 隐藏加载提示
export const hideLoading = () => {
  if (!isWeChatWork()) return

  wx.hideLoading()
}

// 显示消息提示
export const showToast = (title, icon = 'success', duration = 2000) => {
  if (!isWeChatWork()) {
    // 非企业微信环境使用浏览器alert
    alert(title)
    return
  }

  wx.showToast({
    title: title,
    icon: icon, // success, error, loading, none
    duration: duration
  })
}

// 确认对话框
export const showModal = (title, content) => {
  return new Promise((resolve) => {
    if (!isWeChatWork()) {
      // 非企业微信环境使用浏览器confirm
      resolve(confirm(`${title}\n${content}`))
      return
    }

    wx.showModal({
      title: title,
      content: content,
      success: (res) => {
        resolve(res.confirm)
      },
      fail: () => {
        resolve(false)
      }
    })
  })
}

// 拨打电话（企业微信环境优化）
export const makePhoneCall = (phoneNumber) => {
  return new Promise((resolve, reject) => {
    if (!phoneNumber) {
      reject(new Error('电话号码不能为空'))
      return
    }

    if (isWeChatWork()) {
      // 企业微信环境中的拨号
      wx.makePhoneCall({
        phoneNumber: phoneNumber,
        success: (res) => {
          resolve(res)
        },
        fail: (err) => {
          // 如果企业微信拨号失败，降级到浏览器拨号
          window.location.href = `tel:${phoneNumber}`
          resolve()
        }
      })
    } else {
      // 非企业微信环境直接使用浏览器拨号
      window.location.href = `tel:${phoneNumber}`
      resolve()
    }
  })
}

// 获取网络状态
export const getNetworkType = () => {
  return new Promise((resolve) => {
    if (!isWeChatWork()) {
      resolve(navigator.onLine ? 'wifi' : 'none')
      return
    }

    wx.getNetworkType({
      success: (res) => {
        resolve(res.networkType)
      },
      fail: () => {
        resolve('unknown')
      }
    })
  })
}

// 监听网络状态变化
export const onNetworkStatusChange = (callback) => {
  if (!isWeChatWork()) {
    window.addEventListener('online', () => callback(true))
    window.addEventListener('offline', () => callback(false))
    return
  }

  wx.onNetworkStatusChange((res) => {
    callback(res.isConnected)
  })
}

// 获取设备信息
export const getSystemInfo = () => {
  return new Promise((resolve) => {
    if (!isWeChatWork()) {
      resolve({
        platform: navigator.platform,
        version: navigator.appVersion
      })
      return
    }

    wx.getSystemInfo({
      success: (res) => {
        resolve(res)
      },
      fail: () => {
        resolve({})
      }
    })
  })
}

export default {
  WECHAT_CONFIG,
  isWeChatWork,
  getWeChatUserInfo,
  wechatLogin,
  getWeChatJsApiConfig,
  selectContact,
  shareToExternal,
  setNavigationBar,
  showLoading,
  hideLoading,
  showToast,
  showModal,
  makePhoneCall,
  getNetworkType,
  onNetworkStatusChange,
  getSystemInfo
}